#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <U8g2lib.h>

WiFiClient client;
HTTPClient http;
U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, D5, D6);

void setup()
{
    Serial.begin(115200);
    WiFi.mode(WIFI_STA);
    WiFi.begin("LIUYU", "12345678");
    while (!WiFi.isConnected())
    {
        delay(500);
        Serial.print('.');
    }
    Serial.println(WiFi.localIP());
    u8g2.begin();
    u8g2.setFont(u8g2_font_wqy15_t_gb2312);
}

void loop()
{

    http.begin(client, "http://hq.sinajs.cn/list=s_sh000001,s_sz399001");
    if (http.GET() == HTTP_CODE_OK)
    {
        String line;

        while ((line = http.getStream().readStringUntil('\n')) && (line != ""))
        {
            String stock[6];
            int begin = line.indexOf('"');
            int end = line.lastIndexOf('"');
            line = line.substring(begin + 1, end);
            //Serial.println(line);
            for (int i = 0; i < 6; i++)
            {
                int delim = line.indexOf(',');
                stock[i] = line.substring(0, delim);
                line = line.substring(delim + 1);
                Serial.println(stock[i]);
            }
            u8g2.clearBuffer(); //清空缓冲区
            u8g2.drawUTF8(0, 15, "上证指数");
            //u8g2.drawStr(0, 15, stock[0].c_str());//U8g2只支持UTF8字符的显示，服务器返回的中文是GB2312编码
            u8g2.drawUTF8(0, 30, stock[1].c_str());
            u8g2.drawUTF8(0, 45, stock[2].c_str());
            u8g2.drawUTF8(0, 60, String(stock[3] + "%").c_str());
            u8g2.sendBuffer(); //显示缓冲区内容
            delay(5000);
        }
    }
    http.end();
}
